package de.preisrobot.business.parser;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import de.preisrobot.entity.Artikel;
import de.preisrobot.service.helper.HttpClientFactory;
import de.preisrobot.service.internal.PreisRobotParserException;

public abstract class AbstractParser implements Parser
{
   private Logger log = Logger.getLogger(AbstractParser.class);
   
   @Override
   public List<Artikel> parse(String sourceUrlString) throws Exception {

      List<Artikel> list = new ArrayList<Artikel>();

      if (sourceUrlString == null || sourceUrlString.length() == 0)
         throw new RuntimeException("Using default argument of \""
               + sourceUrlString + '"');

      HttpClient client = HttpClientFactory.getHttpClient();
      GetMethod method = HttpClientFactory.createGETMethod(sourceUrlString);
      client.executeMethod(method);

      try {
         
         InputStream in = method.getResponseBodyAsStream();
         parseStream(list, in);
         
      }
      catch(PreisRobotParserException e)
      {
         throw e;
      }
      catch (Exception e) {
         
         log.error(e);

      } finally {
         
         method.releaseConnection();
      }
      return list;
   }

   public abstract void parseStream(List<Artikel> list, InputStream in) throws IOException, PreisRobotParserException;

   public abstract void parseStream(List<Artikel> list, Reader in) throws IOException, PreisRobotParserException;
  
  
}
